﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Reflection;
using System.Collections;

namespace Dynamo.Core.Materializer
{
	public class Materializer : IMaterializer
	{
		private Type			tObjectType;
		private XmlTextReader	xtrXmlTextReader;

		#region IMaterializer Members

		public TObjectType Materialize<TObjectType>(string sObjectData)
		{
			throw new NotImplementedException();
			object oObjectData;

			tObjectType = typeof(TObjectType);

			System.Text.UTF8Encoding encoder = new UTF8Encoding();
			xtrXmlTextReader = new XmlTextReader(new MemoryStream(encoder.GetBytes(sObjectData)));

			xtrXmlTextReader.XmlResolver = null;

			xtrXmlTextReader.Read();
			xtrXmlTextReader.MoveToContent();

			oObjectData = MaterializeObject();

			return (TObjectType)oObjectData;
		}

		#endregion

		public object MaterializeObject()
		{
			object oObjectData = tObjectType.Assembly.CreateInstance(xtrXmlTextReader.Name);

			xtrXmlTextReader.Read();
			xtrXmlTextReader.MoveToContent();

			while (!xtrXmlTextReader.EOF)
			{
				PropertyInfo piPropertyInfo = tObjectType.GetProperty(xtrXmlTextReader.Name);

				xtrXmlTextReader.Read();
				xtrXmlTextReader.MoveToContent();

				if (piPropertyInfo.PropertyType == typeof(string))
				{
					piPropertyInfo.SetValue(oObjectData, xtrXmlTextReader.Value, null);
				}
				else if (piPropertyInfo.PropertyType == typeof(int))
				{
					piPropertyInfo.SetValue(oObjectData, int.Parse(xtrXmlTextReader.Value), null);
				}
				else if (piPropertyInfo.PropertyType == typeof(Guid))
				{
					piPropertyInfo.SetValue(oObjectData, new Guid(xtrXmlTextReader.Value), null);
				}
				else if (piPropertyInfo.PropertyType == typeof(IList))
				{
				}
				else if (piPropertyInfo.IsDefined(typeof(ReferenceAttribute), true))
				{
					xtrXmlTextReader.Read();
					xtrXmlTextReader.MoveToContent();

					//

					xtrXmlTextReader.Read();
					xtrXmlTextReader.MoveToContent();
					xtrXmlTextReader.Read();
					xtrXmlTextReader.MoveToContent();
				}
				else
				{
					piPropertyInfo.SetValue(oObjectData, MaterializeObject(), null);
				}

				xtrXmlTextReader.Read();
				xtrXmlTextReader.MoveToContent();

				xtrXmlTextReader.Read();
				xtrXmlTextReader.MoveToContent();
			}

			return oObjectData;
		}
	}
}
